<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="100px">
        <el-form-item label="问题编号">
          <el-input
            v-model="searchParam.qualityProblemCode"
            placeholder="请输入问题编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="问题提出部门">
          <el-tree-select
            placeholder="请选择问题提出部门"
            v-model="searchParam.proposeDepartmentId"
            :data="organizationList"
            :render-after-expand="false"
            :check-strictly="true"
            node-key="id"
            :props="{
              label: 'organizationCode',
              value: 'id',
              children: 'nodes',
            }"
            style="width: 100%"
            clearable
          />
        </el-form-item>

        <el-form-item label="责任部门">
          <el-tree-select
            placeholder="请选择责任部门"
            v-model="searchParam.departmentId"
            :data="organizationList"
            :render-after-expand="false"
            :check-strictly="true"
            node-key="id"
            :props="{
              label: 'organizationCode',
              value: 'id',
              children: 'nodes',
            }"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item label="问题状态">
          <el-select
            v-model="searchParam.releaseState"
            placeholder="请选择问题状态"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList('releaseState2')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="问题分类" prop="problemTypeCode">
          <el-select
            v-model="searchParam.problemTypeCode"
            placeholder="请选择问题分类"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList('ExceptionType')"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="严重程度" prop="exceptionLevel">
          <el-select
            v-model="searchParam.exceptionLevel"
            placeholder="请选择严重程度"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in problemLevelList"
              :key="item.id"
              :label="item.exceptionLevelCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内部外部">
          <el-select
            v-model="searchParam.isInternal"
            placeholder="请选择内部外部"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList('isInternal')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理类型" prop="problemApproachType">
          <el-select
            v-model="searchParam.problemApproachType"
            placeholder="请选择处理类型"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList('ApproachType')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <!-- <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        > -->
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleClose()"
          ><i-ep-delete />批量关闭</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          :selectable="selected"
          width="55"
          align="center"
        />
        <el-table-column
          label="状态"
          prop="releaseState"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              dictionaryStore.filterDictName(
                "releaseState2",
                scope.row.releaseState
              )
            }}
          </template>
        </el-table-column>

        <el-table-column
          label="内部/外部"
          prop="isInternal"
          min-width="180"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              dictionaryStore.filterDictName("isInternal", scope.row.isInternal)
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="处理类型"
          prop="problemApproachType"
          min-width="180"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              dictionaryStore.filterDictName(
                "ApproachType",
                scope.row.problemApproachType
              )
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="问题编号"
          prop="qualityProblemCode"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="问题描述"
          prop="describe"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="机理/原因分析"
          prop="reason"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column label="问题描述" align="center">
          <el-table-column
            label="问题分类"
            prop="problemTypeCode"
            min-width="150"
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              {{
                dictionaryStore.filterDictName(
                  "ExceptionType",
                  scope.row.problemTypeCode
                )
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="问题细分类"
            prop="exceptionTypeSubCode"
            min-width="150"
            show-overflow-tooltip
            align="center"
          />
          <el-table-column
            label="严重度"
            prop="exceptionLevelCode"
            min-width="150"
            show-overflow-tooltip
          />
        </el-table-column>

        <el-table-column
          label="目标设定"
          prop="targetTime"
          min-width="140"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              scope.row.targetTime
                ? dayjs(scope.row.targetTime).format("YYYY-MM-DD")
                : ""
            }}
          </template>
        </el-table-column>

        <el-table-column label="针对问题的纠正">
          <el-table-column
            label="临时或遏制措施"
            prop="temporary"
            min-width="180"
            show-overflow-tooltip
            align="center"
          />
          <el-table-column
            label="完成时间"
            prop="temporaryTime"
            min-width="180"
            show-overflow-tooltip
            align="center"
          />
        </el-table-column>
        <el-table-column label="系统性的纠正措施">
          <el-table-column
            label="纠正措施"
            prop="correct"
            min-width="120"
            show-overflow-tooltip
            align="center"
          />
          <el-table-column
            label="完成时间"
            prop="correctTime"
            min-width="180"
            show-overflow-tooltip
            align="center"
          />
        </el-table-column>
        <el-table-column label="细化完善">
          <el-table-column
            label="其他类似产品、过程的预防"
            prop="prevent"
            min-width="200"
            show-overflow-tooltip
            align="center"
          />
          <el-table-column
            label="完善标准"
            prop="standard"
            min-width="150"
            show-overflow-tooltip
            align="center"
          />
        </el-table-column>
        <el-table-column
          label="问题提出部门"
          prop="proposeDepartmentName"
          min-width="120"
          show-overflow-tooltip
          align="center"
        />

        <el-table-column
          label="责任部门"
          prop="departmentCode"
          min-width="120"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column label="问题解决小组">
          <el-table-column
            label="组长"
            prop="leader"
            min-width="120"
            show-overflow-tooltip
            align="center"
          />
          <el-table-column
            label="成员"
            prop="member"
            min-width="120"
            show-overflow-tooltip
            align="center"
          />
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="460">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>

            <el-button
              type="primary"
              size="small"
              link
              @click="openProSumit(scope.row)"
              :disabled="
                scope.row.isInternal != '0' || scope.row.releaseState != '3'
              "
              ><i-ep-edit />问题确认</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              :disabled="
                scope.row.isInternal != '0' || scope.row.releaseState != '4'
              "
              @click="openSuplSumit(scope.row)"
              ><i-ep-delete />供应商拒绝审核</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              :disabled="
                scope.row.releaseState != '5' && scope.row.releaseState != '6'
              "
              @click="openRating(scope.row)"
              ><i-ep-circleCheck />问题评分</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              :disabled="
                scope.row.releaseState != '5' && scope.row.releaseState != '6'
              "
              @click="down(scope.row.id)"
              ><i-ep-switch />问题关闭</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 评价页面 -->
    <q8dd80-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <!-- 问题确认页面 -->
    <q8dissueclarification-edit
      :visible="addDialog1.visible"
      :title="addDialog1.title"
      :data="addDialog1.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog1.readvisible"
      @change-visible="changeVisible1"
    />
    <!-- 问题澄清页面 -->
    <problemConfirmation-edit
      :visible="addDialog2.visible"
      :title="addDialog2.title"
      :data="addDialog2.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog2.readvisible"
      @change-visible="changeVisible2"
    />
    <!-- 查看 -->
    <lookAllWork
      :visible="addDialogAll.visible"
      :title="addDialogAll.title"
      :data="addDialogAll.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialogAll.readvisible"
      @change-visible="changeVisibleAll"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
// import html2pdf from "./components/PDF.js";
import dayjs from "dayjs";
import { assign } from "lodash-es";
const dictionaryStore = useDictStoreHook();
defineOptions({
  name: "QMSQ8DLSSUECLARIFICATION",
  inheritAttrs: false,
});

function PDFprit() {
  const table = document.getElementById("table");
  // html2pdf(table, {
  //   background: "#fff",
  //   minimumUnit: "tr",
  //   orientation: "l",
  // });
  // html2pdf("table", "对账单", dayjs(new Date()).format("YYYY-mm-dd"));
}

// 请求参数
const requestApi = "/qms/q8dqualityproblem/queryBySolvePage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  qualityProblemCode: "",
  productProjectName: "",
  departmentId: "",
  releaseState: "",
  problemTypeCode: "",
  exceptionLevel: "",
  proposeDepartmentId: "",
  problemApproachType: "",
  isInternal: "",
};

const deleteParam = {
  api: "/qms/q8dqualityproblem/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);
const hh = ref(false);
onMounted(() => {
  getTableList();

  console.log(tableData.value);
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

/** 打开质量问题信息表单弹窗 */
function openRating(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "问题评价";
    addDialog.data = roleObj;
    addDialog.visible = true;
    addDialog.readvisible = true;
  }
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

/** 打开质量问题信息表单弹窗 详情 */
const addDialogAll = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
function openDialogdetail(roleObj?: any) {
  addDialogAll.title = "质量问题清单详情";
  getInfo(roleObj.id);
  addDialogAll.readvisible = true;
  // addDialogAll.visible = true;
  // addDialogAll.data = roleObj;
}

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/qms/q8dqualityproblem/get/${id}`,
    method: "get",
  })
    .then((data) => {
      console.log("查出来的数据", data);

      addDialogAll.data = data.data;
      addDialogAll.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
function changeVisibleAll(value: boolean) {
  console.log("changeVisibleAll", value);

  addDialogAll.visible = value;
  if (!value) {
    addDialogAll.data = {};
  }
}
function getproblemTime(data: any) {
  if (data) {
    searchParam.value.problemTimeStart = data[0];
    searchParam.value.problemTimeEnd = data[1];
  } else {
    searchParam.value.problemTimeStart = "";
    searchParam.value.problemTimeEnd = "";
  }
}
function getapprovalTime(data: any) {
  if (data) {
    searchParam.value.approvalTimeStart = data[0];
    searchParam.value.approvalTimeEnd = data[1];
  } else {
    searchParam.value.approvalTimeStart = "";
    searchParam.value.approvalTimeEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/qms/q8dqualityproblem/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

// 责任部门

const organizationList = ref([]);
const getOrganizationList = async () => {
  let res = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 4 },
  }).finally(() => {});
  organizationList.value = res.data;
};

// 发布按钮
const addDialog1 = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

/** 打开质量问题信息表单弹窗 详情 */
function changeVisible1(value: boolean) {
  addDialog1.visible = value;
  if (!value) {
    addDialog1.data = {};
  }
}

const openProSumit = (row: any) => {
  if (row) {
    addDialog1.title = "问题澄清";
    addDialog1.data = row;
    addDialog1.visible = true;
  } else {
    addDialog1.title = "问题澄清";
    addDialog1.visible = true;
  }
};

// 澄清理由
const addDialog2 = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

/** 打开质量问题信息表单弹窗 详情 */
function changeVisible2(value: boolean) {
  addDialog2.visible = value;
  if (!value) {
    addDialog2.data = {};
  }
}

// 查询详情
async function getMeasureList(id: string) {
  await request({
    url: `/qms/q8dissueclarification/getList`,
    method: "post",
    data: {
      qualityExceptionId: id,
    },
  })
    .then((res) => {
      addDialog2.data = res.data[0];
      addDialog2.visible = true;
      console.log("查出来的数据", addDialog2.data);
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开拒绝供应商审核 */
function openSuplSumit(roleObj?: Object) {
  if (roleObj) {
    addDialog2.title = "对供应商澄清评价";
    getMeasureList(roleObj.id);
    // addDialog2.data = roleObj;
    console.log("addDialog2.data", addDialog2.data);
  } else {
    addDialog2.title = "对供应商澄清评价";
    addDialog2.visible = true;
  }
  addDialog2.readvisible = false;
}
/** 打开质量问题信息表单弹窗 详情 */
function changeVisible3(value: boolean) {
  addDialog2.visible = value;
  if (!value) {
    addDialog2.data = {};
  }
}

// 问题级别
const problemLevelList = ref([]);
const getProblemLevelList = async () => {
  let res = await request({
    url: "/qms/qmsexceptionlevel/getList",
    method: "post",
    data: {},
  }).finally(() => {});
  problemLevelList.value = res.data;
  console.log("problemLevelList", problemLevelList.value);
};

// 问题关闭
const down = async (id) => {
  ElMessageBox.confirm("确定关闭问题吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/qms/q8dqualityproblem/getScore/${id}`,
      method: "post",
    }).then(async (res) => {
      console.log(res.data);
      if (res.data == -1) {
        ElMessageBox.confirm("该问题评分小于90，是否关闭？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            await request({
              url: `/qms/q8dqualityproblem/close`,
              method: "post",
              data: { ids: [id] },
            }).then(() => {
              ElMessage({
                type: "success",
                message: "关闭成功!",
              });
              getTableList();
            });
          })
          .catch(() => {});
      } else {
        await request({
          url: `/qms/q8dqualityproblem/close`,
          method: "post",
          data: { ids: [id] },
        }).then(() => {
          ElMessage({
            type: "success",
            message: "关闭成功!",
          });
          getTableList();
        });
      }
    });
  });
};
const handleClose = () => {};

// 停用过滤
const selected = (row) => {
  if (row.releaseState == 5) {
    return true; //不可勾选
  } else {
    return false; //可勾选
  }
};
onMounted(() => {
  getOrganizationList();
  getProblemLevelList();
});
</script>
